import React from 'react';
import {
    StyleSheet,
    View,
    Text,ScrollView,
    TextInput,Picker,
    TouchableOpacity,
    Image,
} from 'react-native';

import Icon from 'react-native-vector-icons/FontAwesome';
import cStyles, {colors} from '../common/commonStyles';
import Common from '../common/constants';
import * as urls from '../common/constants_url';
import Util from '../common/utils';
import Button                 from '../common/Button';
import Loading from '../components/Loading';
import {getIcon}        from '../common/icons';
import {Toast,ListRow,SearchInput,Select,Label} from 'teaset';

export default class SearchSpace extends React.Component {

  constructor(props) 
  {
    super(props);
    this.state = {
        valueCustom:'',
        selected:[0,1,101,1011],
        endNode:{},
        selectedValue:'',
        orgs:{'0':[
                        {value:1,text:'广东'},
                        {value:2,text:'福建'},
                        {value:3,text:'江苏'},
                        {value:4,text:'浙江'},
                        {value:5,text:'湖南'},
                        ]
                    ,'1':[
                        {value:101,text:'广州'},
                        {value:102,text:'深圳'},
                        {value:103,text:'汕头'},
                        {value:104,text:'东莞'},
                        {value:105,text:'潮汕'},
                        ]
                    ,'101':[
                        {value:1011,text:'越秀'},
                        {value:1012,text:'天河'},
                        {value:1013,text:'黄埔'},
                        {value:1014,text:'荔湾'},
                        {value:1015,text:'海珠'},
                        ]
                    ,'102':[
                        {value:1021,text:'罗湖'},
                        {value:1022,text:'龙岗'},
                        {value:1023,text:'保安'},
                        ]
                    ,'1021':[
                        {value:10211,text:'笋岗'},
                        ]
                    ,'1011':[
                        {value:10111,text:'黄花岗'},
                        {value:10112,text:'区庄'},
                        {value:10113,text:'流花湖'}
                        ]
                    ,'2':[
                        {value:201,text:'福州'},
                        {value:202,text:'厦门'},
                        {value:203,text:'泉州'},
                        {value:204,text:'福清'},
                        {value:205,text:'漳州'},
                        {value:206,text:'龙岩'},
                        ]
        },//是否显示二级菜单{根节点,下一级,下2级，下3级...}
        selectedSubTab:{},//{1:[],2:[]}
        subTab:{},
        tabSelectedColor:'#0066c6',//选中时候的color
        tabColor:'black',//选中时候的color
        valueSM:{}

    };
  }


  //bao
  getRemoteNode(thiz,id,select)
  {
    // let tmpSt=Object.ass select;
    let tmpSt=[]
    if(tmpSt)
    for (var i = 0; i < select.length; i++) {
        tmpSt.push(select[i])
    }
    // let tmpSt=Object.assign({},select)
    let orgs=this.state.orgs;
    let endNode=this.state.endNode;

    if(orgs[id]==undefined)console.log('orgs[id]==undefined');
    if(orgs[id]==undefined&&endNode[id]==undefined)
    {
        this.setState({loading:true});


        let data={pid:id};
        let url=urls.listOrgChildren
        Util.post(url, data,
                (status, code, message, data, share) => {

                    let state={loading:false}
                    if (status) 
                    {
                        if(!data.children)
                        {
                            thiz.setState({loading:false,endNode:state.endNode});
                        }
                        else{

                            let valueSM={}
                            if(select){
                                tmpSt.push(id);

                                valueSM={};

                            }else{
                                valueSM=this.state.valueSM
                            }
                            orgs[id]=data.children;


                            let abc={loading:false,orgs:orgs,valueSM:valueSM};
                            // abc.selected=tmpSt;
                            // console.log('select-2a:state:',abc);


                            thiz.setState(abc);
                            thiz.setState({selected:tmpSt});
                            
                        }
                    } else {
                        thiz.setState({loading:false});
                    }
                    // console.log('orgs:',state);
                    // thiz.setState({loading:false,orgs:state.orgs,selected:state.selected,endNode:state.endNode});
                },
                (error) => {

                    thiz.setState({loading:false})
                    Toast.fail(error);
                }
            );
        }else{

        }
  }

  /**获取子节点*/
  getChildren(thiz,selected,orgs)
  {
    let children=[];
    if(selected)
    {
        for (var i = selected.length - 1; i >= 0; i--) {

            if(orgs[selected[i]]!=undefined)
            {
                children=orgs[selected[i]];
                break;
            }
        }


        // children=orgs[selected[selected.length-1]];
        if(children==undefined){
            thiz.getRemoteNode(thiz,selected);
            children=[]
        }
    }
    return children;
  }
  getRoute(selected,orgs)//0,1,2,3,4
  {

    let result=[];

    let children=orgs;
    let prev='';
    for (var i = 0; i < selected.length; i++) 
    {
        if(i>0){
            if(orgs[prev]!=undefined&&orgs[selected[i]]!=undefined)
            {

                children=orgs[prev];
                for (var ii= 0; ii < children.length; ii++) 
                {
                    if(selected[i]=children[ii].value)
                    {
                        result.push(children[ii]);
                        break;
                    }
                }
            }
        }else{
            result.push({value:0,text:'全国'});
        }

        prev=selected[i];

    }
    return result;

  }

  onPressBtn(thiz,value,text)
  {
    const {selected,orgs,endNode}  = thiz.state;
    let tmpSelect=[];
    for (var i = 0; i < selected.length; i++) 
    {
        tmpSelect.push(selected[i]);
        if(selected[i]==value){
            hasFound=true; 
            break;
        }
    }


    this.setState({selected:tmpSelect,valueSM:{}});
  }



  onSelectChange(thiz,value,text)
  {
    const {selected,orgs,endNode}  = thiz.state;
    //如果存在子节点，则selected+1，子元素valueSM:{}
    if(orgs[value]!=undefined)
    {
        let tmpSelected=selected;

        tmpSelected.push(value);
        valueSM={};
        this.setState({selected:tmpSelected,valueSM:valueSM});   
    }else{

        valueSM={value:value,text:text};
        thiz.setState({valueSM:valueSM});
        if(endNode[value]==undefined){
            //未确定是否有子元素，且还没有查询过后台

            // thiz.getRemoteNode(thiz,value,selected)
        }else{

        }
    }
  }



  onPressParent(thiz,value,text)
  {
    
    const {selected,orgs,endNode}  = thiz.state;
    

    // 如果有子元素，就加到后面



    let tmpSelect=[];
    let hasFound=false;
    let hasChild=false;
    let valueSM={}

    for (var i = 0; i < selected.length; i++) 
    {
        tmpSelect.push(selected[i]);
        if(selected[i]==value){
            hasFound=true; 
            break;
        }
    }


    if(!hasFound)
    {
        if(orgs[value]==undefined)
        {
            if(endNode[value]!=undefined)
            {
                //没有子节点了
                thiz.getChildren(thiz,value,tmpSelect)
            }else{
                // tmpSelect.push(selected[i]);
                valueSM={text:text,value:value};
            }
        }else{
            valueSM={};
            tmpSelect.push(value);
        }
    }

    this.setState({selected:tmpSelect,valueSM:valueSM});
  }



    render() 
    {
        const {selected,orgs}  = this.state;
        let result=this.getRoute(selected,orgs)
        // console.log('result',result);
        let subTabs=[];
        // containerStyle={subtab.containerStyle} style={subtab.style} 
        let mode='dropdown';
        let children=this.getChildren(this,selected,orgs);


        let width=Common.window.width;
        if(this.props.style!=undefined&&this.props.style['height']!=undefined)
        {
            width=this.props.style['height'];
        }

        return (
            <View style={[styles.searchContainer,this.props.style]}>

            <ScrollView horizontal={true} style={[this.props.style]}>

                <View style={{flexDirection: 'column'}}>
                    <View style={{flexDirection: 'row',height:30,borderBottomWidth: 0.5,borderBottomColor: 'gray',width:width}}>
                        {result.map((subtab,i)=>{
                            return (<View style={{flexDirection: 'row',justifyContent: 'flex-end',alignItems: 'center'}}  key={i} ><Button
                            containerStyle={styles.containerStyle}
                            onPress={()=>{this.onPressBtn(this,subtab.value,subtab.text)}} 
                            text={subtab.text} >
                            </Button>
                            <Image style={{width:8,height:8,resizeMode: 'stretch'}} source={getIcon('../images/ic_center_right_arrow.png')}></Image>
                            </View>)
                          })
                        }
                        <Select
                              style={{width: 200, height:30,backgroundColor: '#rgba(238, 169, 91, 0.1)', borderColor: '#8a6d3b'}}
                              value={this.state.valueSM.text?this.state.valueSM.text:''}
                              valueStyle={{flex: 1, color: '#8a6d3b', textAlign: 'right'}}
                              items={children}
                              getItemValue={(item, index) => item.value}
                              getItemText={(item, index) => item.text}
                              iconTintColor='#8a6d3b'
                              placeholder='Select item'
                              pickerTitle='请选择'
                              onSelected={(item, index) => this.onSelectChange(this, item.value,item.text)}
                              />
                        {this.state.loading&&<Text>查询中...</Text>}
                    </View>
                    <View style={{flexDirection: 'row'}}>
                        
                    </View>
                </View>
            </ScrollView>

            </View>
        )
    }
}



const styles = StyleSheet.create({
    searchContainer: {
        flexDirection: 'row',
        height: 64,
        alignItems: 'center',
        borderBottomColor: '#ccc',
        borderBottomWidth: 0.5,
        backgroundColor: 'white',
    },

    textInput: {
        width: Common.window.width - 15 - 30 - 20,
        height: 30,
        marginTop: 9,
        paddingLeft: 5,
        fontSize: 14,
    },

    searchIcon: {
        position: 'absolute',
        right: 15,
        top: 12
    },
    containerStyle:{borderRadius: 2,borderWidth: 0.5,marginLeft:5,marginRight:5,marginBottom:5,height:20}
})